package com.dashboard.cloud.http.service;

import com.dashboard.cloud.common.conts.RemoteCallConts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: spring-cloud-dashboard
 * @Package: com.dashboard.cloud.http.service
 * @ClassName: HttpClientService
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/11/15 12:10
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Slf4j
@Service
public class HttpClientService {

    public String verifyRemoteServer() {
        // 创建URL对象，指定要请求的URL地址
        // 打开连接
        // 设置请求方法为GET
        String response = invokeHttpGetReq(RemoteCallConts.REMOTE_SERVER_STATUS_URI, "GET");
        log.info("{}", response);
        return response;
    }

    private String invokeHttpGetReq(String uri, String method) {
        String body = "";
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            connection.setRequestMethod(method);
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 读取响应内容
            InputStream ins = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            body = response.toString();
            reader.close();
            // 打印响应内容
            log.info("Response Code:{}\nResponse Body:{}", responseCode, response);
            // 关闭连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            log.error("创建远程请求路径失败，", e);
            throw new RuntimeException(e);
        } catch (IOException e) {
            log.error("打开Http连接【{}】失败，", uri, e);
            throw new RuntimeException(e);
        }
        return body;
    }
}